using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 统一的章节保存服务，避免重复的导出章节正文功能
    /// </summary>
    public class UnifiedChapterSaveService
    {
        private readonly ILogger<UnifiedChapterSaveService> _logger;
        private readonly IFileNamingService _fileNamingService;

        public UnifiedChapterSaveService(
            ILogger<UnifiedChapterSaveService> logger,
            IFileNamingService fileNamingService)
        {
            _logger = logger;
            _fileNamingService = fileNamingService;
        }

        /// <summary>
        /// 保存章节内容到项目文件夹
        /// </summary>
        /// <param name="request">保存请求</param>
        /// <returns>保存结果</returns>
        public async Task<ChapterSaveResult> SaveChapterAsync(ChapterSaveRequest request)
        {
            try
            {
                _logger.LogInformation($"开始保存第{request.ChapterNumber}章: {request.ChapterTitle}");

                // 验证请求参数
                var validationResult = ValidateRequest(request);
                if (!validationResult.IsValid)
                {
                    return new ChapterSaveResult
                    {
                        IsSuccess = false,
                        ErrorMessage = validationResult.ErrorMessage
                    };
                }

                // 创建章节目录
                var contentDir = Path.Combine(request.ProjectPath, "章节");
                Directory.CreateDirectory(contentDir);

                // 生成文件名
                var fileName = _fileNamingService.GenerateChapterFileName(
                    request.BookTitle,
                    request.VolumeNumber,
                    request.VolumeName,
                    request.ChapterNumber,
                    request.ChapterTitle,
                    request.FileExtension ?? ".txt");

                var filePath = Path.Combine(contentDir, fileName);

                // 检查并清理重复文件
                await CleanupDuplicateFilesAsync(contentDir, request.BookTitle, request.ChapterNumber, filePath);

                // 保存文件
                await SaveFileAsync(filePath, request.Content, request.FileExtension);

                _logger.LogInformation($"章节保存成功: {filePath}");

                return new ChapterSaveResult
                {
                    IsSuccess = true,
                    FilePath = filePath,
                    FileName = fileName
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存第{request.ChapterNumber}章失败");
                return new ChapterSaveResult
                {
                    IsSuccess = false,
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 批量保存章节
        /// </summary>
        /// <param name="requests">保存请求列表</param>
        /// <returns>保存结果列表</returns>
        public async Task<List<ChapterSaveResult>> SaveChaptersAsync(List<ChapterSaveRequest> requests)
        {
            var results = new List<ChapterSaveResult>();

            foreach (var request in requests)
            {
                var result = await SaveChapterAsync(request);
                results.Add(result);

                // 如果保存失败，记录错误但继续处理其他章节
                if (!result.IsSuccess)
                {
                    _logger.LogWarning($"第{request.ChapterNumber}章保存失败: {result.ErrorMessage}");
                }
            }

            return results;
        }

        /// <summary>
        /// 验证保存请求
        /// </summary>
        private (bool IsValid, string ErrorMessage) ValidateRequest(ChapterSaveRequest request)
        {
            if (string.IsNullOrEmpty(request.ProjectPath))
                return (false, "项目路径不能为空");

            if (string.IsNullOrEmpty(request.BookTitle))
                return (false, "书籍标题不能为空");

            if (string.IsNullOrEmpty(request.Content))
                return (false, "章节内容不能为空");

            if (request.ChapterNumber <= 0)
                return (false, "章节号必须大于0");

            if (!Directory.Exists(request.ProjectPath))
                return (false, $"项目路径不存在: {request.ProjectPath}");

            return (true, string.Empty);
        }

        /// <summary>
        /// 清理重复的章节文件
        /// </summary>
        private async Task CleanupDuplicateFilesAsync(string contentDir, string bookTitle, int chapterNumber, string currentFilePath)
        {
            try
            {
                var pattern = $"*第{chapterNumber}章*";
                var existingFiles = Directory.GetFiles(contentDir, pattern, SearchOption.TopDirectoryOnly)
                    .Where(f => !f.Equals(currentFilePath, StringComparison.OrdinalIgnoreCase))
                    .ToList();

                foreach (var file in existingFiles)
                {
                    try
                    {
                        File.Delete(file);
                        _logger.LogInformation($"删除重复文件: {file}");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, $"删除重复文件失败: {file}");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "清理重复文件时发生错误");
            }
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        private async Task SaveFileAsync(string filePath, string content, string? fileExtension)
        {
            switch (fileExtension?.ToLower())
            {
                case ".txt":
                default:
                    await File.WriteAllTextAsync(filePath, content, Encoding.UTF8);
                    break;
                case ".md":
                    await File.WriteAllTextAsync(filePath, content, Encoding.UTF8);
                    break;
                case ".docx":
                    // 暂时保存为文本文件，后续可以实现Word文档保存
                    var txtPath = Path.ChangeExtension(filePath, ".txt");
                    await File.WriteAllTextAsync(txtPath, content, Encoding.UTF8);
                    _logger.LogWarning($"Word文档保存功能尚未实现，已保存为文本文件: {txtPath}");
                    break;
            }
        }
    }

    /// <summary>
    /// 章节保存请求
    /// </summary>
    public class ChapterSaveRequest
    {
        /// <summary>
        /// 项目路径
        /// </summary>
        public string ProjectPath { get; set; } = string.Empty;

        /// <summary>
        /// 书籍标题
        /// </summary>
        public string BookTitle { get; set; } = string.Empty;

        /// <summary>
        /// 卷号
        /// </summary>
        public int VolumeNumber { get; set; } = 1;

        /// <summary>
        /// 卷名
        /// </summary>
        public string VolumeName { get; set; } = string.Empty;

        /// <summary>
        /// 章节号
        /// </summary>
        public int ChapterNumber { get; set; }

        /// <summary>
        /// 章节标题
        /// </summary>
        public string ChapterTitle { get; set; } = string.Empty;

        /// <summary>
        /// 章节内容
        /// </summary>
        public string Content { get; set; } = string.Empty;

        /// <summary>
        /// 文件扩展名
        /// </summary>
        public string? FileExtension { get; set; } = ".txt";
    }

    /// <summary>
    /// 章节保存结果
    /// </summary>
    public class ChapterSaveResult
    {
        /// <summary>
        /// 是否保存成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 保存的文件路径
        /// </summary>
        public string? FilePath { get; set; }

        /// <summary>
        /// 文件名
        /// </summary>
        public string? FileName { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string? ErrorMessage { get; set; }
    }
}
